<?php
/**
 * 待办事项管理
*/
apf_require_class("Bll_BLL");
apf_require_class("Const_Flow");
apf_require_class("Bll_Flow_ApplyRelation");
apf_require_class("Bll_Flow_OperateLog");
apf_require_class("Bll_Flow_Transfer");
class Bll_Flow_Info extends BLL {

    const ERROR_PARAMS = 1;//参数错误
    const ERROR_UPDATE = 2;//更新失败
    const SUCCESS_CODE = 3;//操作成功
    const FLOW_DONE    = 4;//流程完成
    /**
     * 写入待办事项
     * @param array $data
     * @return boolean
     */
    public function insert_flow($data){
        $res = false;
        if(empty($data) || empty($data['user_id'])){
            return $res;
        }
        return $this->get_flow_dao()->insert($data);
    }
    public function update_flow_data($data,$where){
        $res = false;
        if(empty($data) || empty($where)){
            return $res;
        }
        return $this->get_flow_dao()->update($data,$where);
    }
    /**
     * 修改预计日期
     * @param unknown_type $flow_id
     * @param unknown_type $date
     */
    public function update_plan_date($flow_id,$date){
        $up_status = $this->get_flow_dao()->update_by_id($flow_id,array('effect_date'=>$date));
        $log_bll = new Bll_Flow_OperateLog();
        $up_status = $log_bll->update_plan_date($flow_id,$date);
        return $up_status;
    }
    /**
     * 查看用户是否在正在处理的申请
     * @param unknown_type $uid
     * @param unknown_type $flow_type
     */
    public function check_user_flow($uid,$flow_type=3){
        $_where = array(
            'user_id'=>$uid,
            'flow_type'=>$flow_type,
            'now_status'=>1
            );
        $data = $this->get_flow_dao()->find($_where);
        if(empty($data)){
            return true;
        }
        return false;
    }
    /**
     * 待办事项
     * @param int $flow_id
     */
    public function find_by_id($flow_id){
        return $this->get_flow_dao()->find_by_id($flow_id);
    }
    /**
     * 待办事项
     * @param int $flow_id
     */
    public function find_by_ids($flow_ids){
        return $this->get_flow_dao()->find_by_ids($flow_ids);
    }
    /**
     * 提交某个阶段的动作，查询log表是否满足当前阶段的所有操作都完成，如果完成则进入下一个阶段
     * 每个流程的第一个阶段都不会进入这个流程
     * @param int $flow_id
     * @param array $params
     * @return string 1|参数错误 2|更新失败 3|操作成功 4|流程完成
     */
    public function update_flow($flow_id,$params){
        if(empty($flow_id) || empty($params['flow_type']) || empty($params['flow_stage']) || empty($params['flow_opt'])){
            return self::ERROR_PARAMS;
        }
        $log_bll = new Bll_Flow_OperateLog();
        $datalist = $log_bll->get_flow_log($flow_id);

        if(empty($datalist)){
            return self::ERROR_PARAMS;
        }
        $flow_list = Const_Flow::flow_to_opt();
        //只检测当前阶段是否完成
        $check_role_list = array_keys($flow_list[$params['flow_type']][$params['flow_stage']]);

        //log角色已操作对应的动作
        $log_list = array();
        foreach($datalist as $val){
            $log_list[$val['role_type']] = $val['flow_opt'];
        }
        //是否为技术部
        $is_tech = false;
        if(!empty($params['is_tech'])){
            $is_tech = true;
        }
        //查看日志中属于当前阶段的操作是否都有记录
        $is_allow_role = array();
        //流程都是从第二个阶段开始的使用这个函数
        foreach ($check_role_list as $role_type){
            if(!$is_tech && $role_type==Const_Flow::ROLE_BOOK){
                continue;
            }
            if(empty($log_list[$role_type])){
                $is_allow_role[] = $role_type;
            }
        }

        //是否进入下一阶段
        $updata = array();
        if(isset($params['effect_date'])){
            $updata['effect_date'] = $params['effect_date'];
        }
        $next_stage = '';
        if(empty($is_allow_role)){
            $next_stage = $params['flow_stage']+1;
            if(empty($flow_list[$params['flow_type']][$next_stage])){//如果下一阶段不存在，说明已经完成
                $updata['flow_role_list'] = '';
                $updata['now_status'] = Const_Flow::FLOW_STATUS_EFFECT;
            }else{
                $next_stage_list = $flow_list[$params['flow_type']][$next_stage];
                if(!$is_tech && $params['flow_type'] == Const_Flow::FLOW_TYPE_DIMISSION && $next_stage==Const_Flow::FLOW_DIMISSION_5){
                    unset($next_stage_list[Const_Flow::ROLE_BOOK]);
                }
                $updata['flow_role_list'] = implode(',',array_keys($next_stage_list));
                $updata['flow_stage'] = $params['flow_stage'];//说明当前阶段已经完成,更新到数据库
            }
        }else{//当前阶段还有那些角色没有完成
            $updata['flow_role_list'] = implode(',',$is_allow_role);
        }
        $updata['flow_opt'] = $params['flow_opt'];
        //update flow
        $up_status = $this->get_flow_dao()->update_by_id($flow_id,$updata);
        if(!$up_status){
            return self::ERROR_UPDATE;
        }
        //如果流程完了需要更新所有相关log状态
        if(isset($updata['now_status'])){
            return self::FLOW_DONE;
        }
        return self::SUCCESS_CODE;
    }

    /**
     * 待办事项列表,先查出所有的，再通过查询条件进行过滤
     * @param array $params
     * @param int $limit
     * @param int $offset
     * @return array
     */
    public function get_all_flow_list($params, $limit, $offset,$datatodo = array()){
        $data = array('count'=>0,'datalist'=>array());
         //用于Job 一次性获取所有数据
        if (!empty($datatodo)) {
            $datalist = $datatodo;
        } else {
            if(!empty($params['city_id'])){
                $_where['work_city_id'] = intval($params['city_id']);
            }
            //按类型
            if(!empty($params['flow_type'])){
                $_where[" flow_type IN(".implode(',',$params['flow_type']).") AND 1=?"] = 1;
            }
            //按生效时间
            if(isset($params['start']) && isset($params['end'])){
                $_where["effect_date >= ".$params['start']." AND effect_date<=".$params['end']." AND 1=?"] = 1;
            }
            $_where["now_status"] = 1;//进行中
            $datalist = $this->get_flow_dao()->find($_where,' effect_date DESC,flow_id DESC',0);
            if(empty($datalist)){
                return $data;
            }
        }

        //先初始化下角色基本,每个员工都有可以查看自己
        $allow_uids = array();
        $is_super = !empty($params['role_list'][Const_Flow::ROLE_SUPERIOR]) ? 1 : 0;
        if($is_super){//主管
            $apply_bll = new Bll_Flow_ApplyRelation();
            $sub_data = $apply_bll->get_sub_user($params['user_id']);
            if(!empty($sub_data)){
                foreach($sub_data as $val){
                    $allow_flows[] = $val['flow_id'];
                }
            }
        }
        //员工所有角色能看到阶段和操作
        $role_flow = $this->_build_flow_to_role($params['role_list']);
        $allow_role = array();
        $super_allow_role = array();//主管角色可以处理的操作

        foreach($role_flow as $role=>$val){
            if($role==Const_Flow::ROLE_SUPERIOR){
                continue;
            }
            $role_city = $params['role_list'][$role];
            if(!empty($params['city_id'])){
                if(in_array($params['city_id'],$role_city)){
                    $role_city = array($params['city_id']);
                }else{//当前角色不包含需要查询的城市,continue
                    continue;
                }
            }
            foreach($val as $flow_stage){
                //搜索时按流程类型,过滤不在搜索条件的条件
                if(!empty($params['flow_type']) && !in_array($flow_stage[0],$params['flow_type'])){
                    continue;
                }
                //组合成查看条件 流程类型,流程阶段,#流程操作#,角色,城市=5,11
                foreach($role_city as $value){
                    $allow_role[] = implode(',', array($flow_stage[0],$flow_stage[1],$flow_stage[3],$value));
                }
            }
        }
        //loop 结果集做最终的过滤,记录组合的城市是不是在能查看的角色权限中,同时还不是能看到的uid
        $result = array();
        $tran_bll = new Bll_Flow_Transfer();
        $is_ceo = !empty($params['role_list'][Const_Flow::ROLE_CEO]) ? 1 : 0;
        $is_recruit = !empty($params['role_list'][Const_Flow::ROLE_RECRUIT]) ? 1 : 0;
        $is_sp_hr_uid = APF::get_instance()->get_config('hr_sp_uid');

        //数据库里存的是当前操作，列表显示需要显示下一阶段的操作,需要将已完成的操作转换为下一个操作
        foreach($datalist as $val){
            if(!empty($allow_flows) && in_array($val['flow_id'],$allow_flows)){//审批关系可以的
                $result[] = $val;
                continue;
            }
            //需要给下一阶段的人来查看
            $next_stage = $val['flow_stage']+1;
            //根据角色所能操作的城市过滤
            $check_role = explode(',',$val['flow_role_list']);
            //uid=6214的特殊处理
            if($val['flow_type']==Const_Flow::FLOW_TYPE_TRANSFER || $val['flow_type']==Const_Flow::FLOW_TYPE_MONEY){
                if($val['flow_stage']==Const_Flow::FLOW_TRANSFER_3 || $val['flow_stage']==Const_Flow::FLOW_MONEY_3){
                    if($params['user_id']!=$is_sp_hr_uid){
                        continue;
                    }
                }
                $new_work_city_id=0;
                //异动时,行政由异动后的城市办理,优先退出处理
                if($val['flow_type']==Const_Flow::FLOW_TYPE_TRANSFER && $val['flow_stage']==Const_Flow::FLOW_TRANSFER_5){
                    /*if(!empty($params['role_list'][Const_Flow::ROLE_ADMIN]) && in_array(Const_Flow::ROLE_ADMIN,$check_role)){
                        $flow_data = $tran_bll->get_transfer_by_flow($val['flow_id']);

                        if($flow_data['new_city_id']){//有填岗位
                            $tmp_role_string = $val['flow_type'].','.$next_stage.','.Const_Flow::ROLE_ADMIN.','.$flow_data['new_city_id'];
                            echo $tmp_role_string."<br>";
                            if(!in_array($tmp_role_string,$allow_role)){
                                //$result[] = $val;
                                continue;
                            }
                        }
                    }*/
                    if(!empty($params['role_list'][Const_Flow::ROLE_ADMIN]) && in_array(Const_Flow::ROLE_ADMIN,$check_role)){
                        $flow_data = $tran_bll->get_transfer_by_flow($val['flow_id']);
                        if(!empty($flow_data['new_city_id'])){
                            $new_work_city_id = $flow_data['new_city_id'];
                        }
                    }

                }
            }

            $check_list = array();
            foreach($check_role as $role){
                $wd = ($new_work_city_id && $role==Const_Flow::ROLE_ADMIN && $val['flow_stage']==Const_Flow::FLOW_TRANSFER_5) ? $new_work_city_id : $val['work_city_id'];
                $check_list[] = $val['flow_type'].','.$next_stage.','.$role.','.$wd;
            }

            //招聘如果是编制外的，且阶段是HRD审批的，身份还是ceo直接返回,因为ceo审批可能是多个城市的，
            if($val['flow_type'] == Const_Flow::FLOW_TYPE_RECRUIT){
                if($val['recruit'] && $val['flow_opt']==Const_Flow::PHASE_55 && $is_ceo){
                    $result[] = $val;
                    continue;
                }
            }
            //离职时需要填写交接资料
            if($val['flow_role_list'] == Const_Flow::ROLE_STAFF && $params['user_id'] == $val['user_id']){
                $result[] = $val;
                continue;
            }
            $check_same = array_intersect ($check_list, $allow_role);//没有交集,说明没有权限
            if($check_same){
                if($val['flow_role_list'] == Const_Flow::ROLE_STAFF && $params['user_id'] != $val['user_id']){
                    continue;
                }
                $result[] = $val;
                continue;
            }
        }
        $count = count($result);
        $debug = array(
            'role_list'=>$params['role_list'],
            'where'=>$_where,
            'allow_uids'=>$allow_uids,
            'allow_role'=>$allow_role,
        );
        if(!$limit){//这里是返回能扣作的所有待办事项,首页调用
            return array('count'=>$count,'datalist'=>array());
        }
        //数组分页
        $rs = array_slice($result, $offset,$limit);
        $res_data =  array('count'=>$count,'datalist'=>$rs,'debug'=>$debug);
        return $res_data;
    }
    /**
     *
     * @param array $params
     * @param int $limit
     * @param int $offset
     */
    public function get_recruit_role_list($params, $limit, $offset){
        $data = array('count'=>0,'datalist'=>array());
        //放开权限
        if(!empty($params['flow_type'])){
            $_where[" flow_type IN(".implode(',',$params['flow_type']).") AND 1=?"] = 1;
        }
        //按生效时间
        if(isset($params['start']) && isset($params['end'])){
            $_where["effect_date >= ".$params['start']." AND effect_date<=".$params['end']." AND 1=?"] = 1;
        }
        $role_city = $params['role_list'][Const_Flow::ROLE_RECRUIT];
        if(in_array(11,$role_city)){//上海的流程监控可以全国的招聘流程
            apf_require_class('Bll_Hr_Property');
            $pro_bll = new Bll_Hr_Property();
            $city_list = $pro_bll->get_city_list();
            $role_city = array_keys($city_list);
            $role_city = array_unique($role_city);
        }
        if(!empty($params['role_add'])){
            $it_role_city = $params['role_list'][Const_Flow::ROLE_IT];
            $role_city = array_merge($role_city,$it_role_city);//城市叠加
            $role_city = array_unique($role_city);
        }
        if(!empty($role_city)){
            $_where["work_city_id IN(".implode(',',$role_city).") AND 1=?"] = 1;
        }
        if(!empty($params['city_id'])){
            if(!in_array($params['city_id'],$role_city)){//没有城市的搜索权限权限
                return $data;
            }
            $_where['work_city_id'] = intval($params['city_id']);
        }
        if(!empty($params['now_status'])){
            $_where["now_status"] = intval($params['now_status']);
        }
        $order = ' recruit DESC, effect_date DESC,flow_id DESC';
        $count = $this->get_flow_dao()->find_count($_where);
        if(!$count){
            return $data;
        }
        $datalist = $this->get_flow_dao()->find($_where,$order, $limit,$offset);
        return array('count'=>$count,'datalist'=>$datalist);
    }
    /**
     *
     * @param unknown_type $params
     * @param unknown_type $limit
     * @param unknown_type $offset
     * @return multitype:number multitype:
     */
    public function get_it_role_list($params, $limit, $offset){
        $data = array('count'=>0,'datalist'=>array());
        //按类型
        if(!empty($params['flow_type'])){
            $_where[" flow_type IN(".implode(',',$params['flow_type']).") AND 1=?"] = 1;
        }
        //按生效时间
        if(isset($params['start']) && isset($params['end'])){
            $_where["effect_date >= ".$params['start']." AND effect_date<=".$params['end']." AND 1=?"] = 1;
        }
        $role_city = $params['role_list'][Const_Flow::ROLE_IT];
        if(!empty($role_city)){
            $_where["work_city_id IN(".implode(',',$role_city).") AND 1=?"] = 1;
        }
        if(!empty($params['city_id'])){
            if(!in_array($params['city_id'],$role_city)){//没有城市的搜索权限权限
                return $data;
            }
            $_where['work_city_id'] = intval($params['city_id']);
        }
        $_where["now_status"] = 1;
        $order = ' effect_date DESC,flow_id DESC';
        $count = $this->get_flow_dao()->find_count($_where);
        if(!$count){
            return $data;
        }
        $datalist = $this->get_flow_dao()->find($_where,$order, 0,0);
        foreach($datalist as $k=>$val){
            $check_role = explode(',',$val['flow_role_list']);
            if(!in_array(Const_Flow::ROLE_IT,$check_role)){
                unset($datalist[$k]);
                continue;
            }
            if(!in_array($val['work_city_id'],$role_city)){
                unset($datalist[$k]);
                continue;
            }
        }
        $count = count($datalist);
        $datalist = array_slice($datalist, $offset,$limit);
        return array('count'=>$count,'datalist'=>$datalist);
    }
    /**
     * 根据角色  上海hr可以查看所有的流程 ,it能看全国的
     * @param array $params
     * @param int $limit
     * @param int $offset
     * @return multitype:number multitype:
     */
    public function get_hr_role_list($params, $limit, $offset){
        $data = array('count'=>0,'datalist'=>array());
        //按类型
        if(!empty($params['flow_type'])){
            $_where[" flow_type IN(".implode(',',$params['flow_type']).") AND 1=?"] = 1;
        }
        //按生效时间
        if(isset($params['start']) && isset($params['end'])){
            $_where["effect_date >= ".$params['start']." AND effect_date<=".$params['end']." AND 1=?"] = 1;
        }
        $role_city = $params['role_list'][Const_Flow::ROLE_HR];
        if(!empty($role_city)){
            $_where["work_city_id IN(".implode(',',$role_city).") AND 1=?"] = 1;
        }
        if(!empty($params['city_id'])){
            if(!in_array($params['city_id'],$role_city)){//没有城市的搜索权限权限
                return $data;
            }
            $_where['work_city_id'] = intval($params['city_id']);
        }
        //$order = ' effect_date DESC,flow_id DESC';
        if(!empty($params['now_status'])){
            $_where["now_status"] = intval($params['now_status']);
        }
        $order = ' last_update DESC ';
        $count = $this->get_flow_dao()->find_count($_where);
        if(!$count){
            return $data;
        }
        $datalist = $this->get_flow_dao()->find($_where,$order, $limit,$offset);
        return array('count'=>$count,'datalist'=>$datalist);
    }

    private function _check_next_flow($data,$role_list){
        $flow_list = Const_Flow::flow_to_opt();
        $first_stage = array(
                Const_FLOW::FLOW_ENTRY_1,
                Const_FLOW::FLOW_TRANSFER_1,
                Const_FLOW::FLOW_DIMISSION_1,
                Const_FLOW::FLOW_MONEY_1,
        );

        foreach($flow_list[$data['flow_type']] as $stage=>$role){
            if(in_array($stage,$first_stage)){

            }
        }
    }
    /**
     * 获取入职用户的入职待办事项
     */
    public function get_flow_by_uid($entry_id){
        $entry_id = intval($entry_id);
        if(!$entry_id){
            return 0;
        }
        $result = $this->get_flow_dao()->find(array('user_id'=>$entry_id,'flow_type'=>Const_Flow::FLOW_TYPE_ENTRY));
        if(!empty($result)){
            return $result[0];
        }
        return 0;
    }
    /**
     * 查询一条flow
     */
    public function get_flow_by_id($flow_id){
        $flow_id = intval($flow_id);
        if(!$flow_id){
            return array();
        }
        return $this->get_flow_dao()->find_by_id($flow_id);
    }
    /**
     * 多条查询
     */
    public function get_flow_by_ids($flow_ids){
        $result = array();
        if(!is_array($flow_ids) || empty($flow_ids)){
            return $result;
        }
        return $this->get_flow_dao()->find_by_ids($flow_ids);
    }
    /**
     * 取消该流程
     */
    public function update_flow_cancel($flow_id){
        $flow_id = intval($flow_id);
        if(!$flow_id){
            return 0;
        }
        $data = array('now_status'=>Const_Flow::FLOW_STATUS_CANCEL);
        return $this->get_flow_dao()->update_by_id($flow_id,$data);
    }
    /**
     * 行政或it在hr非正常操作情况下的，待办事项处理
     * 档案录入更新名字
     */
    public function update_flow_entry($flow_id,$data){
        $flow_id = intval($flow_id);
        if(!$flow_id){
            return 0;
        }
        return $this->get_flow_dao()->update_by_id($flow_id,$data);
    }
    /**
     * 根据各阶段的操作按角色归类
     * @return array
     */
    private function _build_flow_to_role($params_role){
        $data = Const_Flow::flow_to_opt();
        $rs = array();
        foreach($data as $flow_type=>$flow_stage_list){
            foreach($flow_stage_list as $flow_stage=>$role_list){
                if(in_array($flow_stage,array(Const_Flow::FLOW_ENTRY_1,Const_Flow::FLOW_DIMISSION_1,Const_Flow::FLOW_TRANSFER_1, Const_Flow::FLOW_MONEY_1))){
                    //continue;
                }
                foreach($role_list as $role_type=>$flow_opt){
                    if(!empty($params_role[$role_type])){
                        $rs[$role_type][] = array($flow_type,$flow_stage,$flow_opt,$role_type);
                    }
                }
            }
        }
        //tp($rs);
        return $rs;
    }

    private function get_flow_dao(){
        $dao = $this->get_dao('Dao_Flow_Flow');
        return $dao;
    }
}
